import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    public static void main(String[] args) {
        int[] nums = {1,0,-1,0,-2,2};
        List<List<Integer>> ret = fourSum(nums,0);
        System.out.println(ret);
    }
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        //排序
        Arrays.sort(nums);
        int n = nums.length;
        List<List<Integer>> ret = new ArrayList<>();
        for(int i = 0; i < n; ) {
            //固定i位置的数字，计算三数之和
            int tmp = nums[i];
            thrreeSum(i,nums,ret,target);
            //去重
            while(i < n && nums[i] == tmp) {
                i++;
            }
        }
        return ret;
    }
    public static void thrreeSum(int one, int[] nums, List<List<Integer>> ret, int target) {
        int start = one + 1;
        for(int i = start; i < nums.length;) {
            twoSum(one,i,nums,ret,target);
            int tmp = nums[i];
            while( i < nums.length && nums[i] ==  tmp) {
                i++;
            }
        }
    }
    public static void twoSum(int one, int two, int[] nums, List<List<Integer>> ret, int target) {
        int left = two+1;
        int right = nums.length - 1;
        while(left < right) {
            if((long)nums[one]+(long)nums[two]+(long)nums[left]
                    + (long)nums[right] > (long)target) {
                right--;
            }else if((long)nums[one]+(long)nums[two]+(long)nums[left]
                    + (long)nums[right] < (long)target) {
                left++;
            }else{
                ret.add(Arrays.asList(nums[one],nums[two],nums[left],nums[right]));
                int tmp = nums[left];
                while( left < right && nums[left] == tmp) {
                    left++;
                }
            }
        }
    }
}
